package com.tlgen.controller;

import com.tlgen.bean.FastDFSFile;
import com.tlgen.utils.FastDFSCient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.IOException;
import java.io.InputStream;

@Controller
public class FileController {

    private static Logger LOGGER = LoggerFactory.getLogger(FileController.class);

    // 上传文件
    @PostMapping("upload")
    public String FileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {
        if (file.isEmpty()) {
            redirectAttributes.addFlashAttribute("message", "请选择一个文件上传!");
            return "redirect:/uploadStatus";
        }
        try {
            // 上传文件拿到返回的文件路径
            String path = saveFile(file);
            redirectAttributes.addFlashAttribute("message", "上传成功! " + file.getOriginalFilename());
            redirectAttributes.addFlashAttribute("path", "路径 " + path);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "redirect:/uploadStatus";
    }

    @GetMapping("/")
    public String upload() {
        return "upload";
    }

    @GetMapping("/uploadStatus")
    public String uploadStatus() {
        return "uploadStatus";
    }

    public String saveFile(MultipartFile multipartFile) throws IOException {
        String[] fileAbsolutePath = {};
        String fileName = multipartFile.getOriginalFilename();
        String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
        byte[] file_buff = null;
        InputStream inputStream = multipartFile.getInputStream();
        if (inputStream != null) {
            int len1 = inputStream.available();
            file_buff = new byte[len1];
            inputStream.read(file_buff);
        }
        inputStream.close();
        FastDFSFile fastDFSFile = new FastDFSFile(fileName, file_buff, ext);
        fileAbsolutePath = FastDFSCient.upload(fastDFSFile);
        if (fileAbsolutePath == null) {
            LOGGER.error("上传失败!");
        }
        String path = FastDFSCient.getTrackerUrl() + fileAbsolutePath[0] + "/" + fileAbsolutePath[1];
        return path;
    }
}
